package com.today.usercenter.ui.activities;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.ActionBar;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.today.lib.common.account.Account;
import com.today.lib.common.permission.PermissionsUtils;
import com.today.lib.common.ui.activity.ChooseImageActivity;
import com.today.lib.common.ui.base.RxBaseActivity;
import com.today.lib.common.utils.FileUtils;
import com.today.lib.common.utils.ToastUtils;
import com.today.lib.common.utils.image.ImageLoader;
import com.today.usercenter.R;
import com.today.usercenter.R2;
import com.today.usercenter.bus.events.LoginEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

import static com.today.usercenter.bus.events.LoginEvent.STATUS_LOGOUT;


public class UserInfoActivity extends RxBaseActivity {

    @BindView(R2.id.info_avatar)
    ImageView mAvatar;
    @BindView(R2.id.info_nick)
    TextView mNickText;
    @BindView(R2.id.info_sex)
    TextView mSexText;
    @BindView(R2.id.dialog_background)
    View mDialogBackground;

    @BindView(R2.id.toolbar)
    QMUITopBar mToolbar;
    @BindView(R2.id.logout)
    Button mLoginBtn;

    private final int REQUEST_CODE_IMAGE = 3;
    private final int REQUEST_CODE_CAMERA = 4;
    private final int REQUEST_CROP = 5;
    private boolean mIsHeadChange; // 头像是否改变
    private String mLocalHeadPicPath;
    private String mAvatarUrl;

    private Account account;

    private View mPopupView;
    private PopupWindow window;

    private Dialog mProgressDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        account = Account.get();

        mAvatarUrl = account.user_headimg;
        ImageLoader.showAvatar(this, mAvatar, mAvatarUrl);
        mNickText.setText(account.getShowName());
        mSexText.setText(account.getShowSex());
        mProgressDialog = new Dialog(this, R.style.progress_dialog);
        View layout = LayoutInflater.from(this).inflate(R.layout.dialog_layout, null);
        mProgressDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));// 设置布局
        mProgressDialog.setCancelable(false);
        mProgressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        ((TextView) mProgressDialog.findViewById(R.id.loading_text)).setText("正在上传头像...");

        initToolbar();


        mProgressDialog.setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() != KeyEvent.ACTION_UP) {
                mProgressDialog.dismiss();
                return true;
            }
            return true;
        });
    }

    private void initToolbar() {
        mToolbar.setBackgroundColor(ContextCompat.getColor(this, com.today.lib.common.R.color.colorPrimary));
        mToolbar.addLeftBackImageButton().setOnClickListener(v -> onBackPressed());
        mToolbar.setTitle(R.string.personal_info);
    }

    @OnClick({R2.id.info_avatar_layout, R2.id.info_nick_layout, R2.id.info_sex_layout, R2.id.logout})
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.info_avatar_layout) {
//            selectHeadPic();
            ToastUtils.showToast("暂不支持修改头像");
        } else if (i == R.id.info_nick_layout) {
            showEditNick();

        } else if (i == R.id.info_sex_layout) {
            showSelectSexDialog();

        } else if (i == R.id.logout) {
            logout();
        }
    }

    private void logout() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage("确定退出登录吗？")
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    dialog.dismiss();

                    Account.get().logout();
                    ToastUtils.showToast("您已退出登录");
                    EventBus.getDefault().post(new LoginEvent(STATUS_LOGOUT));

                    finish();
                })
                .show();
    }


    private void showEditNick() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("标题")
                .setPlaceholder("在此输入您的昵称")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            mNickText.setText(text);
                            updateUserInfo();
                            dialog.dismiss();
                        } else {
                            ToastUtils.showToast("请填入昵称");
                        }
                    }
                }).show();
    }


    private void showSelectSexDialog() {
        int checkedIndex = 0;
        if ("女".equals(mSexText.getText().toString())) {
            checkedIndex = 1;
        }
        final int finanIndex = checkedIndex;
        final String[] items = new String[]{"保密", "男生", "女生"};
        new QMUIDialog.CheckableDialogBuilder(this)
                .setCheckedIndex(checkedIndex)
                .setTitle("请选择性别")
                .addItems(items, (dialog, which) -> {
                    mSexText.setText(items[which]);
                    if (finanIndex != which) {
                        updateUserInfo();
                    }
                    dialog.dismiss();
                }).show();
    }


    // 选择头像或性别
    private void selectHeadPic() {
        mDialogBackground.setVisibility(View.VISIBLE);
        mPopupView = LayoutInflater.from(this).inflate(R.layout.popup_change_avatar, null);
        window = new PopupWindow(mPopupView,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);


        // 实例化一个ColorDrawable颜色透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        window.setBackgroundDrawable(dw);
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.avatar_pop_anim_style);
        // 在底部显示
        window.showAtLocation(mAvatar,
                Gravity.BOTTOM, 0, 0);

        window.setOnDismissListener(() -> mDialogBackground.setVisibility(View.GONE));

        TextView takePhoto = mPopupView.findViewById(R.id.take_photo);
        TextView chooseAlbum = mPopupView.findViewById(R.id.choose_album);
        TextView cancel = mPopupView.findViewById(R.id.cancel);
        takePhoto.setOnClickListener(v -> {
            dismissPopupWindow();
            PermissionsUtils.checkPermissions(UserInfoActivity.this, () -> {
                dismissPopupWindow();
                String tmpDir = FileUtils.getTempDir();

                File file = new File(tmpDir, "head.jpg");
                if (file.exists())
                    file.delete();

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                int currentApiVersion = Build.VERSION.SDK_INT;
                if (currentApiVersion < Build.VERSION_CODES.N) {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                    startActivityForResult(intent, REQUEST_CODE_CAMERA);//采用ForResult打开
                } else {
                    Uri uri = FileProvider.getUriForFile(UserInfoActivity.this, "com.today.ustv.fileProvider", file);
                    //添加权限
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent, REQUEST_CODE_CAMERA);
                }
            }, Manifest.permission.CAMERA);
        });

        chooseAlbum.setOnClickListener(v -> {
            dismissPopupWindow();
            Intent intent = new Intent(UserInfoActivity.this, ChooseImageActivity.class);
            intent.putExtra("type", 1);
            startActivityForResult(intent, REQUEST_CODE_IMAGE);
        });

        cancel.setOnClickListener(v -> dismissPopupWindow());
    }


    private void dismissPopupWindow() {
        if (window != null && window.isShowing()) {
            window.dismiss();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_IMAGE:
                if (data != null && !TextUtils.isEmpty(data.getStringExtra("pic"))) {
                    String pic = data.getStringExtra("pic");
                    cropPhoto(pic);
                }
                break;
            case REQUEST_CODE_CAMERA:
                if (resultCode == RESULT_OK) {
                    if (!new File(FileUtils.getTempDir() + "head.jpg").exists())
                        ToastUtils.showToast("拍照失败？");
                    cropPhoto(FileUtils.getTempDir() + "head.jpg");
                }
                break;
            case REQUEST_CROP:
//                if (data != null) {
//                    Bundle extras = data.getExtras();
//                    if (extras != null) {
//                        Bitmap head = extras.getParcelable("data");
//                        if (head != null) {
//                            mIsHeadChange = true;
//                            ImageLoader.showAvatar(mAvatar, mLocalHeadPicPath);
//                            getQiniuToken();
//                        }
//                    }
//                }
                if (data != null) {
                    mLocalHeadPicPath = data.getStringExtra("imgpath");
                    if (!TextUtils.isEmpty(mLocalHeadPicPath)) {
                        //上传服务器
                        mIsHeadChange = true;
                        ImageLoader.showAvatar(this, mAvatar, mLocalHeadPicPath);
                        getQiniuToken();
                        mProgressDialog.show();
                    }
                    break;
                }
        }
    }


    private void cropPhoto(String pic) {
        Intent intent1 = new Intent(this, HeadImageCropActivity.class);
        intent1.putExtra("imgpath", pic);
        startActivityForResult(intent1, REQUEST_CROP);
    }

    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        mLocalHeadPicPath = FileUtils.getTempDir() + System.currentTimeMillis() + ".jpg";
        intent.putExtra("output", Uri.fromFile(new File(mLocalHeadPicPath)));
        startActivityForResult(intent, REQUEST_CROP);
    }

    private void updateUserInfo() {
//        String nick = mNickText.getText().toString();
//        String sex = mSexText.getText().toString();
//        HashMap<String, String> map = new HashMap<>();
//        map.put("nick", nick);
//        map.put("userimg", mAvatarUrl);
//        map.put("sex", sex);
//        RetrofitHelper.getUserApi()
//                .editInfo(map)
//                .compose(bindToLifecycle())
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(thirdLoginEntity -> {
//                            if ("0".equals(thirdLoginEntity.reCode)) {
//                                SPUtils.put(Account.PREFS_USER_NICKNAME, nick);
//                                SPUtils.put(Account.PREFS_USER_ICON_URL, mAvatarUrl);
//                                SPUtils.put(Account.PREFS_USER_SEX, sex);
//                                CustomToask.showToast("修改成功");
//                                if (mProgressDialog.isShowing()) {
//                                    mProgressDialog.dismiss();
//                                }
//                                EventBus.getDefault().post(new LoginEvent(sex, "", "", "", "", "", "", "", true));
//                            }
//                        }, throwable -> {
//                            CustomToask.showToast("修改失败，请重试");
//                            throwable.printStackTrace();
//                            if (mProgressDialog.isShowing()) {
//                                mProgressDialog.dismiss();
//                            }
//                        }
//                );
    }


    public void getQiniuToken() {
//        RetrofitHelper.getUserApi().getQiniuToken()
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(qiNiuEntity -> {
//                    if (!TextUtils.isEmpty(qiNiuEntity.token)) {
//                        uploadToQiniuHttp(qiNiuEntity.token);
//                    } else {
//                        CustomToask.showToast("图片上传失败");
//                        if (mProgressDialog.isShowing()) {
//                            mProgressDialog.dismiss();
//                        }
//                    }
//                }, throwable -> {
//                    CustomToask.showToast("图片上传失败");
//                    if (mProgressDialog.isShowing()) {
//                        mProgressDialog.dismiss();
//                    }
//                });
    }

    private void uploadToQiniuHttp(String token) {
//        String key = MD5Utils.encode(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())) + "android");
//        QiniuUtils.uploadPic(new File(mLocalHeadPicPath), key, token, new QiniuUtils.UploadPicListener() {
//            @Override
//            public void onSuccess(String imageUrl) {
//                try {
//                    mAvatarUrl = Constants.LEKU_REFERER + "/" + imageUrl;
//                    ImageLoader.showAvatar(UpdateUserInfoActivity.this, mAvatar, mAvatarUrl);
//                    updateUserInfo();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    mAvatarUrl = Constants.LEKU_REFERER + "/" + imageUrl;
//                    if (mAvatar != null) {
//                        ImageLoader.showAvatar(UpdateUserInfoActivity.this, mAvatar, mAvatarUrl);
//                        updateUserInfo();
//                    }
//                }
//            }
//
//            @Override
//            public void onFail() {
//                CustomToask.showToast("图片上传失败");
//                if (mProgressDialog.isShowing()) {
//                    mProgressDialog.dismiss();
//                }
//            }
//        });
    }
}
